package com.cskaoyan.market.shiro;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.db.domain.MarketPermission;
import com.cskaoyan.market.db.domain.MarketPermissionExample;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.mapper.MarketAdminMapper;
import com.cskaoyan.market.db.mapper.MarketPermissionMapper;
import com.cskaoyan.market.service.AdminAuthService;
import com.cskaoyan.market.service.AdminRoleService;
import com.cskaoyan.market.util.Permission;
import com.cskaoyan.market.vo.PermVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminAuthService adminAuthService;

    @Autowired
    AdminRoleService service ;
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        MarketToken usernamePasswordToken = (MarketToken) token;
        String username = usernamePasswordToken.getUsername();
        MarketAdmin markedAdmin = adminAuthService.selectPasswordByName(username);
        return new SimpleAuthenticationInfo(markedAdmin,markedAdmin.getPassword() , getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> perms = new ArrayList<>();
        MarketAdmin admin  = (MarketAdmin) principals.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();
        for (Integer roleId : roleIds) {
            MarketPermissionExample marketPermissionExample = new MarketPermissionExample();
            marketPermissionExample.createCriteria().andRoleIdEqualTo(roleId);
            List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(marketPermissionExample);
            for (MarketPermission marketPermission : marketPermissions) {
                perms.add(marketPermission.getPermission());
            }
        }
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }

}
